<template>
  <el-container>
    <!-- <RegionTree style="margin-top: 16px" @on-choose-region="filetrRegion" /> -->
    <el-main>
      <div class="default-main ba-table-box">
        <!-- 表格顶部菜单 -->
        <TableHeader
          :buttons="['refresh', 'comSearch', 'columnDisplay']"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
      </div>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import {
  ref,
  onUnmounted,
  onMounted,
  provide,
  reactive,
  markRaw,
  onBeforeUnmount,
} from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { EquipMonitor } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import type { TableColumn, TableRow } from "@/utils/baTable"; //表格列行类型
import useCurrentInstance from "@/utils/useCurrentInstance";
import { useBackendMonitor } from "@/store/backend/EquipM/monitor"; //实时设备监控仓库
import { useRouter, useRoute } from "vue-router";
// import RegionTree from "@/components/roleRegionTree/index.vue";
import { useRegion } from "@/store/backend/SysM/region";
import MQTT from "@/utils/mqtt";
import type { MqttClient, OnMessageCallback } from "mqtt";
import { useAccess } from "@/store/backend/DeviceM/access";
import { useBusiness } from "@/store/backend/BusinessM/info";
import Cascader from "@/components/Cascader/index.vue";
import TagState from "@/components/dictTagState/index.vue";
import TagSearch from "@/components/tagSearch/index.vue";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { getDictData } from "@/utils/common";
import { useNavTabs } from "@/store/navTabs";

const tableRef = ref();
const placeholder = ref<string>("模糊搜索");
const monitor = useBackendMonitor();
const router = useRouter();
const region = useRegion();
const access = useAccess();
const route = useRoute();
const dictionary = useDictionary();
const navTabs = useNavTabs();

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 字段显隐记忆功能 字段中有默认隐藏false情况的
const filedShowOffDefault = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(route.path + "/" + filter)
      ? true
      : false;
  }
  return "";
};
// 每页个数记忆功能 默认20个
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + EquipMonitor)
      ? (navTabs as any).pageSizeMap.get(route.path + EquipMonitor)
      : 20;
  }
  return 20;
};

const baTable = new baTableClass(new baTableApi(EquipMonitor), {
  pk: "id",
  column: [
    { type: "selection", align: "center", operator: false },
    {
      show: filedShowOff("eid"),
      label: "网关编号",
      prop: "eid",
      fixed: "left",
      width: "140",
      align: "center",
    },
    {
      show: filedShowOff("ecode"),
      label: "设备编号",
      fixed: "left",
      prop: "ecode",
      align: "center",
    },
    {
      show: filedShowOff("cname"),
      label: "关联企业",
      fixed: "left",
      width: "240",
      prop: "cname",
      align: "center",
      operator: false,
    },
    {
      show: filedShowOff("operating"),
      label: "环保设备运行状态",
      prop: "operating",
      align: "center",
      render: "tag",
      custom: { 0: "info", 1: "success", 2: "danger" },
      replaceValue: {
        0: "未运行",
        1: "运行",
        2: "未知",
      },
    },
    {
      show:
        filedShowOffDefault("production") === ""
          ? false //默认false
          : filedShowOffDefault("production"),
      label: "生产设备运行状态",
      prop: "production",
      align: "center",
      render: "tag",
      custom: { 0: "info", 1: "success", 2: "danger" },
      replaceValue: {
        0: "未运行",
        1: "运行",
        2: "未知",
      },
    },
    {
      show: filedShowOff("state"),
      label: "设备状态",
      prop: "state",
      align: "center",
      width: "90",
      render: "customRender",
      customRender: markRaw(TagState),
      comSearchRender: "customRender",
      comSearchCustomRender: markRaw(TagSearch),
    },
    {
      show: filedShowOff("flow"),
      label: "风速流量",
      prop: "flow",
      align: "center",
      operator: false,
      render: "customTemplate",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + value + " m/s" + "</p>";
      },
    },
    {
      show: filedShowOff("temperature"),
      label: "温度",
      prop: "temperature",
      align: "center",
      operator: false,
      render: "customTemplate",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + value + " &#8451" + "</p>";
      },
    },
    {
      show: filedShowOff("pa"),
      label: "压强",
      prop: "pa",
      align: "center",
      operator: false,
      render: "customTemplate",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + value + " pa" + "</p>";
      },
    },
    {
      show:
        filedShowOffDefault("current") === ""
          ? false //默认false
          : filedShowOffDefault("current"),
      label: "电流",
      prop: "current",
      align: "center",
      operator: false,
      render: "customTemplate",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + value + " A" + "</p>";
      },
    },
    {
      show:
        filedShowOffDefault("voltage") === ""
          ? false //默认false
          : filedShowOffDefault("voltage"),
      label: "电压",
      prop: "voltage",
      align: "center",
      operator: false,
      render: "customTemplate",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + value + " V" + "</p>";
      },
    },
    {
      show:
        filedShowOffDefault("hz") === ""
          ? false //默认false
          : filedShowOffDefault("hz"),
      label: "电频",
      prop: "hz",
      align: "center",
      operator: false,
      render: "customTemplate",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + value + " Hz" + "</p>";
      },
    },
    {
      show: filedShowOff("thisTime"),
      label: "换碳后的运行时长(时)",
      prop: "thisTime",
      align: "center",
      operator: false,
      render: "customTemplate",
      customTemplate: (row: TableRow, field: TableColumn, value: any) => {
        return "<p>" + (value / 3600).toFixed(2) + "</p>";
      },
    },
    {
      show: false,
      label: "选择区域",
      prop: "",
      align: "center",
      comSearchRender: "customRender",
      comSearchCustomRender: markRaw(Cascader),
    },
    {
      show: operatorShowOff([route.path + "/edit"]),
      label: "操作",
      align: "center",
      width: "120",
      render: "buttons",
      fixed: "right",
      buttons: [
        {
          render: "tipButton",
          name: "info", //绑定edit
          title: "详情",
          text: "",
          type: "primary",
          icon: "iconfont icon-chaxunyujisuan",
          class: "table-row-edit",
          disabledTip: false,
          display: (row: TableRow, field: TableColumn) => {
            if (row.state === 2) {
              //未激活状态无法查看实时数据
              return false;
            }
            return true;
          },
          // 按钮是否禁用，请返回布尔值
          disabled: (row: TableRow, field: TableColumn) => {
            return false;
          },
          attr: {},
        },
      ],
      operator: false,
    },
  ],
  filter: {
    regions: region.regionIds + "",
    pageSize: pageSizeKeep(),
  },
});

const PublicMqtt = ref<MQTT | null>(null);
const startMqtt = (val: string, callback: OnMessageCallback) => {
  //设置订阅地址
  PublicMqtt.value = new MQTT(val);
  //初始化mqtt
  PublicMqtt.value.init();
  //链接mqtt
  PublicMqtt.value.link();
  getMessage(callback);
};

//获取订阅数据
const getMessage = (callback: OnMessageCallback) => {
  // PublicMqtt.value?.client.on('message', callback);
  PublicMqtt.value?.get(callback);
};

//取消mqtt订阅
const unsubscribe = () => {
  //如果页面并没有初始化MQTT，无需取消订阅
  if (PublicMqtt.value) {
    PublicMqtt.value.unsubscribes();
  }
};
interface Region {
  address: string | null;
  addressDetail: string | null;
  areaFlag: string | null;
  areaId: number;
  areaName: string | null;
  areaNo: string | null;
  children: Region[];
  createBy: string | null;
  createTime: string | null;
  endTime: string | null;
  params: any;
  parentId: number;
  searchValue: string | null;
  startTime: string | null;
  updateBy: string | null;
  updateTime: string | null;
}

// const filetrRegion = (row: Region, node: any) => {
//   //判断node属性中checkedNodes是否为空
//   if (node.checkedKeys.length == 0) {
//     //实时状态监控表示取消选择直接调用刷新表单方法 数据需要更新
//     baTable.comSearch.form = Object.assign(baTable.comSearch.form, {
//       regions: region.regionIds + "",
//     });
//     baTable.onTableHeaderAction("refresh", {});
//   } else {
//     baTable.comSearch.form.regions = node.checkedKeys + "";
//     baTable.getList(EquipMonitor);
//   }
// };

//查看 id暂为字符串
const infoButtonClick = (name: string, row: anyObj) => {
  // const infoButtonClick = (val: any) => {
  console.log("row", row);
  baTable.form.operate = "info"; //batable当前操作为 单个 info查看
  baTable.form.loading = true; //打开loading
  //从后台获取该设备数据跳转详情页
  // monitor
  //   .getnowList({ eid: row.eid })
  //   .then((res) => {
  //     access.getDevicesItem(row.ecode).then((res: any) => {
  //       //处理coordinate坐标系
  //       res.data.coordinate = JSON.parse(res.data.coordinate);
  //       monitor.deviceData = res.data;
  //       //为基本信息处理所属企业Map数据格式问题
  //       const business = useBusiness();
  //       const { companyList } = business;
  //       if (companyList.length === 0) {
  //         //为空就重新获取企业列表数据
  //         business.getCompanyList();
  //       }
  //     });
  //   })
  //   .catch((err) => {
  //     console.log(err);
  //   });
  monitor
    .getnowList({ eid: row.eid })
    .then((res) => {
      access
        .getDeviceByGateway(row.ecode, region.regionIds)
        .then((res: any) => {
          //处理coordinate坐标系
          res.rows[0].coordinate = JSON.parse(res.rows[0].coordinate);
          monitor.deviceData = res.rows[0];
          //为基本信息处理所属企业Map数据格式问题
          const business = useBusiness();
          const { companyList } = business;
          if (companyList.length === 0) {
            //为空就重新获取企业列表数据
            business.getCompanyList();
          }
        });
    })
    .catch((err) => {
      console.log(err);
    });
  router.push({ path: "/admin/EquipM/Monitordetail", query: { eid: row.eid } });
};
type RootObject = {
  equipid: number;
  name: string;
  avatar: string;
  owner_auth: number;
  user_auth: number;
  remark: string;
  is_online: number;
  is_alarm: number;
  is_running: number;
  status: number;
  last_parser_time: number;
  wind_speed: string;
  temperature: string;
  pa: string;
  carbonUse: string;
  dev_name: string;
  current_value_sensorid: number;
  current_value_updatetime: number;
  tags: any[];
  electric: string;
  voltage: string;
  address: string; //单个设备具体地址
  company_name: string; //隶属于公司或个人 名称
  parent_company_id: number; //相关联企业id
  company_address: string; //公司具体地址
  company_location: string; //公司经纬度
  contact: string; //代理人 可联系人名称或称呼
  te: string; //联系电话
};

//获取菜单状态的字典
const getMenuStatus = () => {
  dictionary.getDictInfo("device_online_status").then((res: any) => {
    // state.statusDict = getDictData(res);
    dictionary.tag = getDictData(res);
    console.log("获取菜单状态的字典", dictionary.tag);
  });
};
getMenuStatus();

const state: { endLine: number; startTime: any; end: boolean } = reactive({
  endLine: 5 * 1000 * 1000,
  startTime: new Date().getTime(),
  end: false,
});

//轮询请求
const restart = async (): Promise<any> => {
  if (state.end) {
    return;
  }
  // 这里的remoteCall是一个虚拟的函数，指代需要轮询的http接口
  const response = await monitor.getList({
    regions: region.regionIds + "",
    pageNum: baTable.table.filter.pageNum,
    pageSize: baTable.table.filter.pageSize,
  });
  console.log("response", response);

  // 这里的状态可以基于http，也可以自己定义自己的结构来处理。这里用200和非200做一个事例
  if (response.code !== 200) {
    return response;
  } else {
    baTable.table.data = response.rows;
    baTable.table.total = response.total;
    // 这里可以看情况设定一个间隔时间。
    // 复杂一点的可以设定一些间隔时间策略： 比如根据请求次数增加，增加间隔时间等等
    // 这里只是一个例子，等待5秒
    await new Promise((resolve) => setTimeout(resolve, 20000));
    return await restart();
  }
};

const newGetList = () => {
  return new Promise((resolve, reject) => {});
};

onMounted(() => {
  //全局事件总线
  const { proxy } = useCurrentInstance();
  //开始连接mqtt
  // startMqtt('CmdSub_338222112334', (topic, message) => {
  //     const msg = JSON.parse(message.toString());
  //     console.log(msg);
  // });
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(EquipMonitor);
  setTimeout(() => {
    restart();
  }, 20000);
  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow | RootObject }) => {
      if (!baTable.activate) return;
      //回滚功能暂无
      if (data.name == "rollback") {
        // onRollback([data.row[baTable.table.pk!]])
      } else if (data.name == "info") {
        //携带主键字段pk
        infoButtonClick(
          (data.row as TableRow)[baTable.table.pk!],
          data.row as RootObject
        );
      }
    }
  );
});

onBeforeUnmount(() => {
  state.end = true;
});
onUnmounted(() => {
  //页面销毁结束订阅
  if (PublicMqtt.value) {
    PublicMqtt.value.unsubscribes();
    PublicMqtt.value.over();
  }
});

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
</script>
<style lang="scss" scoped>
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
.el-main {
  padding: 0;
}
</style>
